package com.java1234.service.impl;

import com.java1234.entity.DeptPerformanceDTO;
import com.java1234.entity.Jixiaokaohe;
import com.java1234.entity.PerformanceEvaluation;
import com.java1234.mapper.JixiaokaoheMapper;
import com.java1234.service.JixiaokaoheService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 绩效考核 服务实现类
 * </p>
 *
 * @author zhai
 * @since 2025-05-09
 */
@Service
public class JixiaokaoheServiceImpl extends ServiceImpl<JixiaokaoheMapper, Jixiaokaohe> implements JixiaokaoheService {

    @Autowired
    private JixiaokaoheMapper jixiaokaoheMapper;
    /**
     * 获取所有月份的绩效考核数据
     */
    @Override
    public List<PerformanceEvaluation> getAllPerformanceEvaluations() {
        return baseMapper.findAllMonthPerformanceEvaluations();
    }

    /**
     * 获取指定时间范围内的绩效考核数据
     * @param startMonth 开始月份 (格式: YYYY-MM)
     * @param endMonth 结束月份 (格式: YYYY-MM)
     */
    @Override
    public List<PerformanceEvaluation> getPerformanceEvaluationsByDateRange(String startMonth, String endMonth, String username) {
        return baseMapper.findPerformanceEvaluationsByDateRange(startMonth, endMonth,username);
    }


    @Override
    public List<String> getAvailableMonths() {
        // 1. 从数据库查询所有有记录的月份
        List<String> months = jixiaokaoheMapper.selectAvailableMonths();

        // 2. 如果没有数据，返回最近12个月
        if (months.isEmpty()) {
            LocalDate now = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

            for (int i = 0; i < 12; i++) {
                months.add(now.minusMonths(i).format(formatter));
            }
            Collections.reverse(months);
        }

        return months;
    }
    @Override
    public List<DeptPerformanceDTO> getDeptPerformanceAnalysis(String startMonth, String endMonth) {
        // 1. 获取所有员工绩效数据
        List<PerformanceEvaluation> employeePerformances = jixiaokaoheMapper
                .findPerformanceEvaluationsByDateRange(startMonth, endMonth, null);

        // 2. 按部门和月份分组
        Map<String, Map<String, List<PerformanceEvaluation>>> deptMonthMap = employeePerformances.stream()
                .collect(Collectors.groupingBy(
                        PerformanceEvaluation::getDepartment,
                        Collectors.groupingBy(PerformanceEvaluation::getPerformanceMonth)
                ));

        // 3. 计算每个部门每月的平均绩效
        List<DeptPerformanceDTO> result = new ArrayList<>();
        deptMonthMap.forEach((dept, monthMap) -> {
            monthMap.forEach((month, evaluations) -> {
                DeptPerformanceDTO dto = new DeptPerformanceDTO();
                dto.setDepartmentName(dept);
                dto.setMonth(month);

                // 计算平均分
                double avgScore = evaluations.stream()
                        .mapToDouble(PerformanceEvaluation::getPerformanceScore)
                        .average()
                        .orElse(0);
                dto.setAvgScore(Math.round(avgScore * 100) / 100.0);

                // 设置绩效等级
                dto.setPerformanceLevel(getPerformanceLevel(avgScore));

                // 设置员工人数
                dto.setEmployeeCount(evaluations.size());

                result.add(dto);
            });
        });

        // 4. 按部门和月份排序
        result.sort(Comparator
                .comparing(DeptPerformanceDTO::getDepartmentName)
                .thenComparing(DeptPerformanceDTO::getMonth).reversed());

        return result;
    }
    private String getPerformanceLevel(double score) {
        if (score >= 90) return "优秀";
        if (score >= 80) return "良好";
        if (score >= 70) return "一般";
        if (score >= 60) return "合格";
        return "不合格";
    }
}
